<template>
  <n-card title="算法离线仓库" :bordered="false" class="h-full">
    <!-- 新增搜索和上传区域 -->
    <n-space justify="space-between" align="center" class="mb-4">

      <div class="flex flex-col items-center mb-4">
        <n-input
          v-model:value="searchValue"
          placeholder="请输入算法名称或ID"
          clearable
          class="w-full"
          style="height: 48px; font-size: 16px; padding: 12px 16px; "
          @input="handleSearch"
        />
      </div>
      <n-upload
        multiple
        :file-list="uploadFiles"
        @change="handleFileChange"
        :show-file-list="false"
      >
        <n-button type="primary">
          <template #icon>
            <n-icon>
              <UploadOutlined />
            </n-icon>
          </template>
          上传算法包
        </n-button>
      </n-upload>
    </n-space>
    <div class="flex-1 overflow-auto">
      <n-grid cols="1 400:2 600:3 800:4" x-gap="12" y-gap="12">
        <n-gi v-for="algorithm in algorithms" :key="algorithm.id">
          <n-card hoverable>
            <template #header>
              <n-text strong>{{ algorithm.chineseName }}</n-text>
              <n-text depth="3" class="ml-2">({{ algorithm.englishName }})</n-text>
            </template>

            <n-space vertical>
              <n-text>算法ID: {{ algorithm.code }}</n-text>
              <n-text>版本: {{ algorithm.version }}</n-text>
              <n-tag :type="algorithm.is_installed ? 'true' : 'false'">
                {{ algorithm.isInstalled ? '已安装' : '未安装' }}
              </n-tag>
            </n-space>

            <template #action>
              <n-button
                v-if="algorithm.installed"
                type="error"
                size="small"
                @click="handleUninstall(algorithm)"
              >
                卸载
              </n-button>
              <n-button
                v-else
                type="primary"
                size="small"
                @click="handleInstall(algorithm)"
              >
                安装
              </n-button>
            </template>
          </n-card>
        </n-gi>
      </n-grid>
    </div>
    <n-pagination
      v-model:page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :item-count="pagination.itemCount"
      :page-sizes="pagination.pageSizes"
      show-size-picker
      show-quick-jumper
      class="mt-4"
      @update:page="fetchAlgorithms"
      @update:page-size="fetchAlgorithms"
    >
    </n-pagination>
  </n-card>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref} from 'vue'
import { useMessage } from 'naive-ui'
import { UploadOutlined } from '@vicons/antd'
import {
  Algorithm,
  GetAlgorithms, InstallAlgorithm,
  UninstallAlgorithm,
  UploadAlgorithms
} from "@/api/warehouse/offline_repos";

const message = useMessage()
const searchValue = ref('') // 搜索值
const uploadFiles = ref<File[]>([])
// 显示上传弹窗
const showUploadModal = ref(false)
const uploadStatus = ref<{ fileName: string; status: 'success' | 'error' }[]>([])
const algorithms = ref<Algorithm[]>([])

// 处理上传
async function handleFileChange(options: { fileList: File[] }) {
  const allowedTypes = ['application/zip', 'application/x-gzip']
  const allowedExtensions = ['.zip', '.tar.gz']
  // 过滤不符合要求的文件
  uploadFiles.value = options.fileList.filter(file => {
    const extension = file.name.slice(file.name.lastIndexOf('.'))
    return allowedTypes.includes(file.type) || allowedExtensions.includes(extension)
  })

  // 如果有被过滤掉的文件，提示用户
  if (options.fileList.length !== uploadFiles.value.length) {
    message.warning('仅支持上传zip或tar.gz格式的安装包')
  }

  if (uploadFiles.value.length === 0) return

  // 显示上传弹窗
  showUploadModal.value = true
  uploadStatus.value = []

  try {
    for (const file of uploadFiles.value) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('folder', 'models')

      try {
        const response = await UploadAlgorithms(formData)
        if (response) {
          uploadStatus.value.push({ fileName: file.name, status: 'success' })
          message.success(`上传成功: ${file.name}`)
        } else {
          uploadStatus.value.push({ fileName: file.name, status: 'error' })
          message.error(`上传失败: ${file.name} `)
        }
      } catch (error) {
        uploadStatus.value.push({ fileName: file.name, status: 'error' })
        message.error(`上传失败: ${file.name}`)
      }
    }
  } finally {
    // 上传完成后刷新算法清单
    fetchAlgorithms()
  }
}

const isLoading = ref(false) // 添加加载状态
// 添加fetchAlgorithms方法
async function fetchAlgorithms() {
  isLoading.value = true
  try {
    const response = await GetAlgorithms({
      page: pagination.page,
      pageSize: pagination.pageSize
    })

    algorithms.value = response.map(algorithm => ({
      id: algorithm.id,
      code: algorithm.code,
      chineseName: algorithm.chineseName,
      englishName: algorithm.englishName,
      version: algorithm.version,
      level: algorithm.level,
      is_used: algorithm.is_used,
      is_installed: algorithm.is_installed,
    }))

    // 更新分页总数
    pagination.itemCount = response.length

  } catch (error) {
    message.error('获取算法清单失败，请检查网络连接')
    console.error('获取算法清单失败:', error)
  }finally {
    isLoading.value = false
  }
}

// 添加分页相关状态
const pagination = reactive({
  page: 1,
  pageSize: 8,
  itemCount: 0, // 添加总条数
  showSizePicker: true,
  pageSizes: [8, 16, 24],
  showQuickJumper: true
})

const loading = ref(false);
// 安装算法
async function handleInstall(algorithm) {
  try {
    loading.value = true;
    message.loading(`正在安装 ${algorithm.chineseName}...`, { duration: 0 });
    await InstallAlgorithm(algorithm.id);

    message.destroyAll();
    message.success(`成功安装 ${algorithm.chineseName}`);
    algorithm.is_installed = true;
  } catch (error) {
    message.error(`安装 ${algorithm.chineseName} 失败`);
    console.error("安装失败:", error);
  } finally {
    loading.value = false;
  }
}

async function handleUninstall(algorithm) {
  try {
    loading.value = true;
    message.loading(`正在卸载 ${algorithm.chineseName}...`, { duration: 0 });

    // 调用卸载接口
    await UninstallAlgorithm(algorithm.id);

    message.destroyAll();
    message.success(`成功卸载 ${algorithm.chineseName}`);
    algorithm.is_installed = false;
  } catch (error) {
    message.error(`卸载 ${algorithm.chineseName} 失败`);
    console.error("卸载失败:", error);
  } finally {
    loading.value = false;
  }
}

// 在组件挂载时调用fetchAlgorithms
onMounted(() => {
  fetchAlgorithms()
})



</script>

<style scoped>
.n-card {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.n-card__action {
  margin-top: auto;
}

.flex-1 {
  flex: 1;
}

.overflow-auto {
  overflow: auto;
}
</style>
